CFLAGS:= -m32
CFLAGS+= -nostdinc
CFLAGS+= -fno-pic
CFLAGS+= -fno-builtin
CFLAGS+= -fno-pie
CFLAGS+= -nostdlib
CFLAGS+= -fno-stack-protector
CFLAGS:=$(strip ${CFLAGS})

NOWALL = -w
SRC = .

objs = 	build/kernel/start.o				\
		build/kernel/main.o					\
		build/kernel/printk.o				\
		build/kernel/acpi.o 				\
		build/kernel/debug.o 				\
		build/kernel/memory.o 				\
		build/kernel/mutex.o 				\
		build/kernel/ush.o  				\
		build/kernel/interrupt.o 			\
		build/kernel/handler.o 				\
		build/kernel/global.o 				\
		build/kernel/syscall.o 				\
		build/kernel/kmalloc.o  				\
		build/kernel/task.o		 			\
		build/kernel/thread.o 				\
		build/kernel/switch.o 				\
		build/kernel/io.o 					\
											\
		build/device/console.o 				\
		build/device/keyboard.o				\
		build/device/tty.o					\
		build/device/timer.o				\
		build/device/ide.o					\
		build/device/device.o				\
											\
		build/lib/string.o 					\
		build/lib/syscall.o 				\
		build/lib/vsprintf.o  				\
		build/lib/bitmap.o  				\
		build/lib/list.o  					\
		build/lib/stdlib.o 					\
		build/lib/fifo.o  					\
		build/lib/printf.o  				\

.PHONY:build/master.img
build/master.img:build/boot/boot.bin build/boot/loader.bin build/kernel.bin
	qemu-img create -f raw build/master.img 32M
	dd if=build/boot/boot.bin of=build/master.img count=1 conv=notrunc
	dd if=build/boot/loader.bin of=build/master.img count=4 seek=2 conv=notrunc
	dd if=build/kernel.bin of=build/master.img seek=10 count=200 conv=notrunc
	qemu-img convert $@ -f raw -O vmdk build/lucnx.vmdk

build/%.bin:$(SRC)/%.asm
	nasm -f bin $< -o $@
build/%.o:$(SRC)/%.asm
	nasm -f elf32 $< -o $@
build/%.o:$(SRC)/%.c
	gcc -c $(CFLAGS) $(NOWALL) -I $(SRC)/include/ $< -o $@

build/kernel.bin:$(objs)
	ld -static -m i386pe $^ -o build/kernel.o -Ttext 0x10000
	objcopy -O binary build/kernel.o $@
	nm build/kernel.o | sort > build/kernel.map

.PHONY:qemu bochsg cloc
qemu:
	qemu-system-i386 -hda build/master.img -m 32M
qemug:build
	qemu-system-i386 -hda build/master.img -m 32M -S -s

dir:
	rm -rf build
	mkdir build
	mkdir build/kernel
	mkdir build/boot
	mkdir build/device
	mkdir build/lib

build:build/master.img

run:build qemu

bochs:build bochsg

bochsg:
	make -C ../bochs

cloc:
	cloc-1.98 ./